
import { Toast } from 'react-vant';
const initialState = {
    arr:[],
    shoparr:JSON.parse(window.localStorage.getItem("shopcar"))||[],
    cheackall: localStorage.getItem("checkall") === "true" ? true : false// 全选按钮是否高亮
}

let shopreducer =  (state = initialState, { type, payload }) => {
  switch (type) {

  case "getlist":
      let newArr = [...state.arr]
      newArr = payload 
      return {
          ...state,
          arr:newArr
      }
  case "addshop":
      let newShoparr = [...state.shoparr]
      let findIndex = newShoparr.findIndex(item=>{
          return item.id  === payload.id
      })
      if (findIndex === -1) {
        newShoparr.push(payload)
      } else {
          alert("您已经加入过购物车了")
      }
      localStorage.setItem("shopcar",JSON.stringify(newShoparr))
      return {
          ...state,
          shoparr:newShoparr
      }
  case "addFn" :
      let addshoparr = [...state.shoparr]
      addshoparr.forEach(item=>{
          if (item.id === payload) {
              item.num ++
          }
      })
      localStorage.setItem("shopcar",JSON.stringify(addshoparr))
      return {
          ...state,
          shoparr:addshoparr
      }
  case "RemoveFn" :
      let removeshoparr =[...state.shoparr]
      removeshoparr.forEach(item=>{
        if (item.id === payload ) {
            item.num -- 
            if (item.num < 1) {
                item.num = 1
                Toast.fail('您不能在减去了')
            }
        } 

    })
    localStorage.setItem("shopcar",JSON.stringify(removeshoparr))
    return {
        ...state,
        shoparr:removeshoparr
    }
  case "changeFn" :
      let checkshoparr = [...state.shoparr] 
      checkshoparr.forEach((item)=>{
          if (item.id === payload) {
              item.flag = !item.flag
          }
      })
      let flagall = checkshoparr.every((item)=>item.flag)
      localStorage.setItem("shopcar",JSON.stringify(checkshoparr))
      localStorage.setItem("checkall",flagall.toString())
      return {
          ...state,
          shoparr:checkshoparr,
          cheackall:flagall
      }
   
  case "checkallfn":
      let shopallarr = [...state.shoparr]
      let newcheackall = state.cheackall
      newcheackall = !newcheackall
      shopallarr.forEach((item)=>{
          item.flag = newcheackall
      })
      localStorage.setItem("checkall",newcheackall.toString())
      localStorage.setItem("shopcar",JSON.stringify(shopallarr))
      return {
          ...state,
          cheackall:newcheackall,
          shoparr:shopallarr
      }
  default:
    return state
  }
}
export default shopreducer
